package com.venus.mq.netty.client;

import com.venus.mq.model.Topic;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * Created by mc on 18/5/29.
 * netty客户端
 */
public class NettyClient {

    private static EventLoopGroup group = new NioEventLoopGroup();
    private static Bootstrap b = new Bootstrap();
    private static Channel ch;


    /**
     * 初始化netty 通道
     * @param socketAddress
     * @return
     */
    public static void initChanel(InetSocketAddress socketAddress){
        try {
            System.out.println("客户端成功启动...");
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.handler(new NettyClientFilter());
            // 连接服务端
            ch = b.connect(socketAddress.getHostName(), socketAddress.getPort()).sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送信息
     * @param topic
     */
    public static void sendMsg(Topic topic){
        ch.writeAndFlush(topic);
        System.out.println("客户端发送数据:"+topic.toString());
    }


   /* public static void star(InetSocketAddress socketAddress ,Topic topic) throws IOException{
        try {
            System.out.println("客户端成功启动...");
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.handler(new NettyClientFilter());
            // 连接服务端
            ch = b.connect(socketAddress.getHostName(), socketAddress.getPort()).sync().channel();
            ch.writeAndFlush(topic);
            System.out.println("客户端发送数据:"+topic.toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }*/

    /**
     * Netty创建全部都是实现自AbstractBootstrap。
     * 客户端的是Bootstrap，服务端的则是    ServerBootstrap。
     **/
    public static void main(String[] args) throws InterruptedException, IOException {
        String str="Hello Netty";
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",6789);
        Topic topic = new Topic();
        topic.setTopicName("test");
        topic.setContent("我的测试队列");
        initChanel(socketAddress);
        sendMsg(topic);
    }

}